package com.kye.express.business.waybill_search;

import android.arch.lifecycle.Lifecycle;

import com.google.gson.reflect.TypeToken;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.LifecycleOpenApiResultObserver;
import com.kye.express.contract.base.view.ErrorView;
import com.kye.express.contract.base.view.LoadingView;
import com.kye.express.contract.base.view.RxView;
import com.kye.model.ApiService;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.SharedPreferencesConfig;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.user.User;
import com.kye.model.bean.waybill_search.RequestWaybillQuery;
import com.kye.model.bean.waybill_search.ResultWaybillQuery;
import com.kye.model.bean.waybill_search.WaybillHistoryModel;
import com.kye.model.service.WaybillQueryService;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.SingleObserver;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public interface WaybillSearchActivityContract {

    interface WaybillSearchView extends RxView, LoadingView, ErrorView {

        void onHistoryLoaded(List<WaybillHistoryModel> datas);

        void onHistoryEmpty();

        void onLoaded(ResultWaybillQuery datas, String searchString);
    }

    class WaybillSearchViewPresenter extends BasePresenter<WaybillSearchView> {

        public void loadHistoryDatas() {
            Observable<List<WaybillHistoryModel>> listObservable = SharedPreferencesManager.getForRx(SharedPreferencesConfig.KEY_HISTORY_WAYBILL, new TypeToken<List<WaybillHistoryModel>>() {
            }.getType());
            listObservable.compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<WaybillHistoryModel>>() {
                        @Override
                        public void accept(List<WaybillHistoryModel> waybillHistoryModels) throws Exception {
                            if (waybillHistoryModels.isEmpty()) {
                                getView().onHistoryEmpty();
                            }

                            getView().onHistoryLoaded(waybillHistoryModels);

                        }
                    });
        }

        public void clearHistoryDatas() {
            SharedPreferencesManager.removeForRx(SharedPreferencesConfig.KEY_HISTORY_WAYBILL)
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SingleObserver<Boolean>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(Boolean aBoolean) {
                            getView().onLoaded();
                        }

                        @Override
                        public void onError(Throwable e) {
                            getView().onLoaded();
                        }
                    });
        }

        public void searchWaybill(final String expressNum) {
            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .flatMap(new Function<User, SingleSource<OpenApiResult<ResultWaybillQuery>>>() {
                        @Override
                        public SingleSource<OpenApiResult<ResultWaybillQuery>> apply(User user) throws Exception {
                            return RetrofitManager.getInstance().createOpenApiService(WaybillQueryService.class)
                                    .waybillQuery(new RequestWaybillQuery(expressNum, user.getPhone()));
                        }
                    })
                    .doOnSuccess(new Consumer<OpenApiResult<ResultWaybillQuery>>() {
                        @Override
                        public void accept(OpenApiResult<ResultWaybillQuery> resultWaybillQueryOpenApiResult) throws Exception {
                            List<WaybillHistoryModel> waybillHistoryModelList = SharedPreferencesManager.get(SharedPreferencesConfig.KEY_HISTORY_WAYBILL, new TypeToken<List<WaybillHistoryModel>>() {
                            }.getType());
                            waybillHistoryModelList.add(new WaybillHistoryModel(expressNum, System.currentTimeMillis()));
                            SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_HISTORY_WAYBILL, waybillHistoryModelList);
                        }
                    })
                    .compose(getView().getProvider().<OpenApiResult<ResultWaybillQuery>>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new OpenApiResultObserver<ResultWaybillQuery>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<ResultWaybillQuery> result, ResultWaybillQuery data) {
                            getView().onLoaded(data, expressNum);
                        }

                        @Override
                        public void onApiError(OpenApiResult<ResultWaybillQuery> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    }));
        }
    }
}
